package com.da.javatest.interview.session2;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/3/30 22:53
 * @description 阻塞队列
 */
public class Test15BlockingQueue {
    public static void main(String[] args) throws InterruptedException {
        // api1();
        // api2();
        // api3();
        BlockingQueue<String> bq = new ArrayBlockingQueue<>(3);
        System.out.println(bq.offer("a", 2, TimeUnit.SECONDS));
        System.out.println(bq.offer("a", 2, TimeUnit.SECONDS));
        System.out.println(bq.offer("a", 2, TimeUnit.SECONDS));
        //System.out.println(bq.offer("a", 2, TimeUnit.SECONDS));

        System.out.println(bq.poll(2, TimeUnit.SECONDS));
        System.out.println(bq.poll(2, TimeUnit.SECONDS));
        System.out.println(bq.poll(2, TimeUnit.SECONDS));
        System.out.println(bq.poll(2, TimeUnit.SECONDS));
    }

    /**
     * 阻塞
     */
    private static void api3() throws InterruptedException {
        BlockingQueue<String> bq = new ArrayBlockingQueue<>(3);
        bq.put("a");
        bq.put("a");
        bq.put("a");
        System.out.println("======================");
        // bq.put("a");

        bq.take();
        bq.take();
        bq.take();
        bq.take();
    }

    /**
     * 多放返回false，多取返回null
     */
    private static void api2() {
        BlockingQueue<String> bq = new ArrayBlockingQueue<>(3);
        System.out.println(bq.offer("a"));
        System.out.println(bq.offer("b"));
        System.out.println(bq.offer("c"));
        System.out.println(bq.offer("d"));  // false

        System.out.println(bq.peek());

        System.out.println(bq.poll());
        System.out.println(bq.poll());
        System.out.println(bq.poll());
        System.out.println(bq.poll());  // null
    }

    /**
     * 多放多取都会抛异常
     */
    private static void api1() {
        BlockingQueue<String> bq = new ArrayBlockingQueue<>(3);
        System.out.println(bq.add("a"));
        System.out.println(bq.add("b"));
        System.out.println(bq.add("c"));
        //bq.add("d"); Queue full

        System.out.println(bq.element());

        System.out.println(bq.remove());
        System.out.println(bq.remove());
        System.out.println(bq.remove());
        // System.out.println(bq.remove()); NoSuchElementException
    }
}
